package com.dyrj.ysk.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dyrj.pig.bean.TUser;
import com.dyrj.pig.bean.TYskPay;
import com.dyrj.pig.dao.TUserMapper;
import com.dyrj.pig.dao.TYskPayMapper;
import com.dyrj.pig.service.TYskPayService;
import com.dyrj.utils.UUIDUtil;
import com.dyrj.ysk.configuration.SdkProperties;
import com.dyrj.ysk.constants.BankCode;
import com.dyrj.ysk.constants.ClientType;
import com.dyrj.ysk.constants.PayModeNo;
import com.dyrj.ysk.constants.SubType;
import com.dyrj.ysk.exception.BizException;
import com.dyrj.ysk.service.SignService;
import com.dyrj.ysk.util.FakeDataUtil;
import com.dyrj.ysk.util.FormUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 前台交易控制器
 * @author 吴侠志  2019/10/18
 * @version 1.0
 */
@Slf4j
@Controller
@RequestMapping("/ysksdk")
public class FrontPayController {
    @Autowired
    private SdkProperties sdkProperties;
    @Autowired
    private SignService signService;
    @Resource
    private TYskPayMapper tYskPayMapper;
    @Resource
    private TUserMapper tUserMapper;

    private DecimalFormat df = new DecimalFormat("0.00");

    /**
     * CLOUDPAY6001
     * 跳转收银台
     * @return
     */
    @RequestMapping(value = "/cashierDesk",method = RequestMethod.GET)
    public void cashierDesk(HttpServletRequest request, HttpServletResponse response) throws BizException, IOException {

        String membercode = request.getParameter("membercode")==null ? "" : request.getParameter("membercode");
        String subno = request.getParameter("subno")==null ? "" : request.getParameter("subno");
        String str_tranamt = request.getParameter("tranamt")==null ? "" : request.getParameter("tranamt");
        int int_tranamt = Integer.valueOf(str_tranamt);
        double dbl_tranamt = Double.valueOf(str_tranamt)/100.0;

        Date now = new Date();
        QueryWrapper<TUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("subno",subno);
        TUser tuser = tUserMapper.selectOne(queryWrapper);

        String payModel = "1";
        if(tuser!=null && tuser.getPaymodel()!=null && !"".equals(tuser.getPaymodel())){
            payModel = tuser.getPaymodel();
        }

        Map<String,String> params=new HashMap<>();
        //商户编号
        params.put("TraderNo",sdkProperties.getBusinessId());
        //客户号
        params.put("ClientNo",membercode);
        //商户订单号
        String TraderOrderNo = FakeDataUtil.randomTraderOrderNo();
        params.put("TraderOrderNo",TraderOrderNo);
        //交易金额 整数，单位：分
        params.put("TranAmt",str_tranamt);
        //订单发送时间
        String OrderSendTime = FakeDataUtil.orderSendTimeNow();
        params.put("OrderSendTime", OrderSendTime);
        //订单名称
        params.put("OrderName","充值");
        String suborderId = FakeDataUtil.randomSuborderId(sdkProperties.getUid());
        //商户备注信息
//        params.put("OrderRemark","[{'oderlist': [{'PayModel': '1', 'SubAccNo': '400000000001111', 'TranFee': '0.01'}], 'SFJOrdertype': '0', 'plantCode': '5030', 'remarktype': 'SDS0100000'}]");
        String OrderRemark = "[{'SFJOrdertype':'1','oderlist':[{'SubAccNo':'"+subno+"','subamount':'"+df.format(dbl_tranamt)+"','PayModel':'"+payModel+"','object':'充值','suborderId':'"+suborderId+"','TranFee':'0.00'}],'remarktype':'JHS0100000','plantCode':'"+sdkProperties.getMrchcode()+"'}]";
        params.put("OrderRemark",OrderRemark);

        /*
        3947000000001008
        [{"SFJOrdertype":"1-子订单信息",
"oderlist":[
{"SubAccNo":"入账会员子账户","subamount":"0.01","PayModel":"0-冻结支付 1-普通支付","object":"飞机票","suborderId":"20003111462017120510040000","TranFee":"0.01"},
{"SubAccNo":"入账会员子账户","subamount":"0.01","PayModel":"0-冻结支付 1-普通支付","object":"飞机票","suborderId":"20003111462017120510040000","TranFee":"0.01"},
{"SubAccNo":"入账会员子账户","subamount":"0.01","PayModel":"0-冻结支付 1-普通支付","object":"飞机票","suborderId":"20003111462017120510040000","TranFee":"0.01"}
],
"remarktype":"备注类型-JHS0100000",
"plantCode":"平台代码"}]

         */

        //登录类型 pc/h5
//        params.put("ClientType", ClientType.PC.getCode());
        params.put("ClientType", ClientType.H5.getCode());
        //前端跳转url
//        params.put("FrontSkipUrl",FakeDataUtil.frontSkipUrl());
        params.put("FrontSkipUrl","http://118.190.52.185:8080/ysk/pay/jumpUrl");
//        params.put("FrontSkipUrl","http://localhost:9999/ysk/pay/jumpUrl");
        //回调通知url
//        params.put("CallBackNoticeUrl",FakeDataUtil.callBackNoticeUrl());
        params.put("CallBackNoticeUrl","http://118.190.52.185:8080/ysk/pay/notify");
        //签名值
        String signature=signService.sign(params,sdkProperties.getPrivateKey());
        params.put("Signature",signature);
        log.info("req:"+JSON.toJSONString(params));
        String form= FormUtil.createAutoFormHtml(sdkProperties.getCashierDeskUrl(),params);
        //如果接口调用成功，将请求的相关参数入库，用于后端通知获取参数关联
        try{
            TYskPay tYskPay = new TYskPay();
            tYskPay.setId(UUIDUtil.uuid());
            tYskPay.setUserid(tuser.getYhbm().toString());
            tYskPay.setClientno(membercode);
            tYskPay.setSubaccno(subno);
            tYskPay.setTraderno(sdkProperties.getBusinessId());
            tYskPay.setTraderorderno(TraderOrderNo);
            tYskPay.setRemark(OrderRemark);
            tYskPay.setTranamt(str_tranamt);
            tYskPay.setOrdersendtime(OrderSendTime);
            tYskPay.setSuborderid(suborderId);
            tYskPay.setInsertime(now);
            tYskPay.setUpdatetime(now);
            tYskPayMapper.insertSelective(tYskPay);
        }catch (Exception e){
            e.printStackTrace();
        }

        log.info("returnMap:"+form);
        response.addHeader("Content-Type", "text/html;charset=utf-8");
        response.getWriter().write(form);
    }
    /**
     * CLOUDPAY6002
     * 绑卡跳转
     * @return
     */
    @RequestMapping(value = "/bindCard",method = RequestMethod.GET)
    public void bindCard(HttpServletRequest request, HttpServletResponse response) throws BizException, IOException {

        String membercode = request.getParameter("membercode")==null ? "" : request.getParameter("membercode");

        Map<String, String> params = new HashMap<>();
        //商户编号
        params.put("TraderNo", sdkProperties.getBusinessId());
        //客户号
        params.put("ClientNo", membercode);

        //必填 签约流水号
        params.put("AgreementNo", FakeDataUtil.randomAgreeSeqNo());
        //必填 订单发送时间 格式：yyyyMMddHHmmss
        params.put("AgreeSendTime",FakeDataUtil.orderSendTimeNow());

//        //非必填 付款人账号
//        params.put("PayerAcctNo",FakeDataUtil.payerAcctNo());
//        //非必填 付款人户名
//        params.put("PayerAcctName",FakeDataUtil.payerAcctName());
//        //非必填 付款人证件类型
//        params.put("PayerGlobalType", PayerGlobalType.ID.getCode());
//        //非必填 付款人证件号码
//        params.put("PayerGlobalId",FakeDataUtil.payerGlobalId());
//        //非必填 付款人预留手机号码
//        params.put("PayerReserverMobile",FakeDataUtil.payerReserverMobile());
//        //非必填 签约类型 理财余额支付签约：1  银联协议支付签约：不上送
//        //params.put("SignType",SignType.LCYE.getCode());

        //绑卡流水号
//        params.put("BindCardSeqNo",FakeDataUtil.randomBindCardSeqNo());
        //绑卡时间
//        params.put("OrderSendTime", FakeDataUtil.orderSendTimeNow());
        //登录类型  pc：pc端,h5：移动端
        params.put("ClientType", ClientType.H5.getCode());
//        params.put("ClientType", ClientType.H5.getCode());
        //前端跳转url
//        params.put("FrontSkipUrl", FakeDataUtil.frontSkipUrl());
        params.put("FrontSkipUrl", "http://118.190.52.185:8080/ysk/bindcard/jumpUrl");
//        params.put("FrontSkipUrl", "http://localhost:9999/ysk/bindcard/jumpUrl");
//        params.put("FrontSkipUrl", "http://localhost:9999/ysksdk/jumpUrl");
        //回调通知url
//        params.put("CallBackNoticeUrl",FakeDataUtil.callBackNoticeUrl());
        params.put("CallBackNoticeUrl","http://118.190.52.185:8080/ysk/bindcard/notify");
        //签名值
        String signature=signService.sign(params,sdkProperties.getPrivateKey());
        params.put("Signature",signature);
        log.info("req:"+JSON.toJSONString(params));
        String form= FormUtil.createAutoFormHtml(sdkProperties.getBindCardUrl(),params);
        log.info("returnMap:"+form);
        response.addHeader("Content-Type", "text/html;charset=utf-8");
        response.getWriter().write(form);

    }
    /**
     * CLOUDPAY6003
     * 网关支付跳转
     * @param response
     * @throws BizException
     * @throws IOException
     */
    @RequestMapping(value = "/unionPay",method = RequestMethod.GET)
    public void unionPay(HttpServletResponse response) throws BizException, IOException {
        Map<String, String> params = new HashMap<>();
        //商户编号
        params.put("TraderNo", sdkProperties.getBusinessId());
        //商户订单号
        params.put("TraderOrderNo",FakeDataUtil.randomTraderOrderNo());
        //订单发送时间
        params.put("OrderSendTime", FakeDataUtil.orderSendTimeNow());
        //支付方式编号 可选值为B2B，B2C，WAP，OnlineGateway
        params.put("PayModeNo", PayModeNo.B2C.getCode());
        //交易金额 单位：分
        params.put("TranAmt", String.valueOf(707));
        //订单名称
        params.put("OrderName", "鸡蛋");
        //通道类型 支付方式为B2C时必填
        params.put("SubType", SubType.DEBIT_CARD.getCode());
        //银行编码 支付方式为B2B和B2C时填
        params.put("BankCode", BankCode.ABC.getCode());
        //银行卡号 当支付方式代码为WAP和OnlineGateway时必填
        params.put("BankCardNo", "9559981700000000004");
        //订单备注
        params.put("OrderRemark", "[{'oderlist': [{'PayModel': '1', 'SubAccNo': '400000000001111', 'TranFee': '0.01'}], 'SFJOrdertype': '0', 'plantCode': '5030', 'remarktype': 'SDS0100000'}]");
        //前端跳转url
        params.put("FrontSkipUrl",FakeDataUtil.frontSkipUrl());
        //回调通知url
        params.put("CallBackNoticeUrl",FakeDataUtil.callBackNoticeUrl());
        //签名值
        String signature=signService.sign(params,sdkProperties.getPrivateKey());
        params.put("Signature",signature);
        log.info("req:"+JSON.toJSONString(params));
        String form= FormUtil.createAutoFormHtml(sdkProperties.getUnionPayUrl(),params);
        log.info("returnMap:"+form);
        response.addHeader("Content-Type", "text/html;charset=utf-8");
        response.getWriter().write(form);
    }


 }